package me.lc.hammerheads.core;

import java.util.Date;
import java.util.Random;

import com.wiyun.engine.nodes.Director;
import com.wiyun.engine.nodes.Scheduler;
import com.wiyun.engine.nodes.Timer;
import com.wiyun.engine.utils.TargetSelector;

import me.lc.hammerheads.entity.BGType;
import me.lc.hammerheads.entity.GameStageInfo;
import me.lc.hammerheads.layer.GameLayer;
import me.lc.hammerheads.scene.GameScene;
import me.lc.hammerheads.util.AudioHelper;

/**
 * 游戏逻辑管理器
 * 
 * @author Administrator
 * 
 */
public class GameManager {
	public static GameManager instance = new GameManager();
	public boolean isPaused = false;
	public boolean isFailed = false;
	public boolean isFinished = false;
	/**
	 * 游戏类型，1.关卡2.无尽
	 */
	public int gameType = 1;

	Random r = new Random((new Date()).getTime());
	private Object doubleHammerSyncObj = new Object();
	private int doubleHammerCount = 0;
	private BGType currentBgType;

	public BGType getCurrentBgType() {
		return currentBgType;
	}

	private GameManager() {
		ts = new TargetSelector(this, "dwarfRefreshTask(float)",
				new Object[] { 0f });
	}

	TargetSelector ts;
	Timer dwarfRefreshTimer;
	int dwarfCount = 0;
	int finishDwarfCount = 0;
	GameStageInfo stageInfo;
	GameLayer gameLayer;

	// 游戏得分相关
	boolean isAddedHeart = false;
	int currentHeart = 5;
	int dwarfScore = 0;
	int knockCount = 0;
	int successCount = 0;
	float rate = 0.0f;
	public int knockOutCount = 0;

	public boolean isAddedHeart() {
		return isAddedHeart;
	}

	public void setAddedHeart(boolean isAddedHeart) {
		this.isAddedHeart = isAddedHeart;
	}

	public synchronized void addDwarfScore(int value) {
		dwarfScore += value;
	}

	public int getLeftHealth() {
		return currentHeart;
	}

	public int getDwarfScore() {
		return dwarfScore;
	}

	public float getSuccessRate() {
		return rate;
	}

	public synchronized void knockResult(boolean isSuccess) {
		knockCount++;
		if (isSuccess) {
			successCount++;
		}
		if (knockCount > 0) {
			rate = successCount / (float) knockCount;
		}
	}

	/**
	 * 开始无尽游戏,不能使用爱心道具
	 * 
	 */
	public void startUnlimitGame() {
		// TODO LC 无尽模式下道具条需要改变样式
		gameType = 2;
		startGame(-1);
	}

	/**
	 * 
	 * @param stageIndex
	 */
	public void startStageGame(int stageIndex) {
		gameType = 1;
		startGame(stageIndex);
	}

	private void startGame(int stageIndex) {
		if (dwarfRefreshTimer != null) {
			Scheduler.getInstance().unschedule(dwarfRefreshTimer);
			dwarfRefreshTimer = null;
		}

		StageManager.instance.doubleHammerCount = 0;

		this.gameLayer = GameScene.make().gameLayer;
		gameLayer.initSprites();
		currentHeart = 5;
		isAddedHeart = false;
		dwarfScore = 0;
		knockCount = 0;
		successCount = 0;
		rate = 0.0f;
		knockOutCount = 0;

		if (stageIndex >= 0) {
			stageInfo = StageManager.instance.stageInfoLst.get(stageIndex);
		} else {
			// 如果传入的值是-1，是无尽模式
			stageInfo = StageManager.instance.umlimitStage;
		}

		dwarfCount = 0;
		finishDwarfCount = 0;
		// dwarfRefreshTimer = new Timer(ts, stageInfo.getDwarfInterval());
		dwarfRefreshTimer = new Timer(ts,
				stageInfo.getDwarfInterval() / 1000.0f);
		Scheduler.getInstance().schedule(dwarfRefreshTimer);
		// dwarfRefreshTimer.schedule(new DwarfRefreshTask(), 1000,
		// stageInfo.getDwarfInterval());

		gameLayer.stageShower.showStageShower(stageInfo.getStageName());
		// 设置游戏背景
		GameScene.make().gameBgLayer.changeBg(stageInfo.getBgType());
		// 生成游戏地图
		GameMap.instance.gen(gameLayer, stageInfo);
		currentBgType = stageInfo.getBgType();
		isPaused = false;
		isFailed = false;
		isFinished = false;
		AudioHelper.go();
	}

	public void dwarfRefreshTask(float lastInterval) {
		if (isPaused) {
			return;
		}
		// if (dwarfCount <= stageInfo.getDwarfCount()) {
		int dwarfShowCount = 1;
		int temp = r.nextInt(100);
		if (temp < 70) {
			dwarfShowCount = 1;
		} else if (temp < 96) {
			dwarfShowCount = 2;
		} else {
			dwarfShowCount = 3;
		}

		// if (dwarfCount + dwarfShowCount > stageInfo.getDwarfCount()) {
		// dwarfShowCount = 1;
		// }

		for (int i = 0; i < dwarfShowCount; i++) {
			int dwarfIndex = getDwarfIndex(r.nextInt(100), stageInfo);
			GameMap.instance.addNewDwarf(dwarfIndex);
			if (gameType == 1) {
				dwarfCount++;
			}
		}

		// TODO lc 随机生成鸭子，金币，或者爱心
		int luckeyRand = r.nextInt(30);
		if (luckeyRand == 1) {
			// duck
			GameMap.instance.addNewDwarf(101);
		}

		// }
	}

	/**
	 * 获取矮人编号
	 * 
	 * @param dwarfRand
	 * @param stageInfo
	 * @return 1.普通 2.普通女 3.铁桶 4.炸弹 5.金属人
	 */
	private int getDwarfIndex(int dwarfRand, GameStageInfo stageInfo) {
		int temp = dwarfRand;
		int result = 0;
		if (temp < stageInfo.getNormalPercentage()) {
			result = 1;
		} else {
			temp -= stageInfo.getNormalPercentage();
			if (temp < stageInfo.getDoubleFemalePercentage()) {
				result = 2;
			} else {
				temp -= stageInfo.getDoubleFemalePercentage();
				if (temp < stageInfo.getDoubleMalePercentage()) {
					result = 3;
				} else {
					temp -= stageInfo.getDoubleMalePercentage();
					if (temp < stageInfo.getBombPercentage()) {
						result = 4;
					} else {
						temp -= stageInfo.getBombPercentage();
						if (temp < stageInfo.getSilverPercentage()) {
							result = 5;
						}
					}
				}
			}
		}
		return result;
	}

	/**
	 * 增加或减少爱心
	 * 
	 * @param addValue
	 */
	public synchronized void changeGameHeart(boolean isAdd) {

		int sub = isAdd ? 1 : -1;
		currentHeart += sub;
		if (currentHeart > 5) {
			currentHeart = 5;
		} else if (currentHeart < 0) {
			currentHeart = 0;
		}
		gameLayer.heartBar.updateHeart(currentHeart);
		if (currentHeart <= 0) {
			if (!isFailed) {
				failedGame();
			}
		}
	}

	/**
	 * 补满血
	 */
	public synchronized void fullHeart() {
		currentHeart = 5;
		gameLayer.heartBar.updateHeart(currentHeart);
	}

	public synchronized void bombAllDwarf() {
		GameMap.instance.knockOutAllDwarf();
	}

	private synchronized void failedGame() {
		// 游戏失败
		isPaused = true;
		isFailed = true;
		if (dwarfRefreshTimer != null) {
			Scheduler.getInstance().unschedule(dwarfRefreshTimer);
			dwarfRefreshTimer = null;
		}
		if (gameType == 1) {
			gameLayer.showLose();
		} else {
			gameLayer.showWin();
		}
		GameMap.instance.pauseAllDwarf();
		AudioHelper.stopMusic();
	}

	private synchronized void finishGame() {
		// 游戏完成
		isFinished = true;
		isPaused = true;
		if (dwarfRefreshTimer != null) {
			Scheduler.getInstance().unschedule(dwarfRefreshTimer);
			dwarfRefreshTimer = null;
		}
		gameLayer.showWin();
		GameMap.instance.pauseAllDwarf();
		AudioHelper.stopMusic();

	}

	/**
	 * 暂停游戏
	 */
	public synchronized void pauseGame() {
		if (!isPaused) {
			isPaused = true;
			gameLayer.pauseGame();
			GameMap.instance.pauseAllDwarf();
		}
	}

	public synchronized void resumeGame() {
		if (isPaused) {
			isPaused = false;
			gameLayer.resumeGame();
			GameMap.instance.resumeAllDwarf();
		}
	}

	public void quitGame() {
		if (dwarfRefreshTimer != null) {
			Scheduler.getInstance().unschedule(dwarfRefreshTimer);
			dwarfRefreshTimer = null;
		}
		isPaused = true;
	}

	public void updateGold() {
		gameLayer.pauseBlock.updateGold();
	}

	private int maxDoubleHammerCount = 20;

	public void addDoubleHammerCount(int value) {
		synchronized (doubleHammerSyncObj) {
			doubleHammerCount += value;
			if (doubleHammerCount > maxDoubleHammerCount) {
				doubleHammerCount = maxDoubleHammerCount;
			} else if (doubleHammerCount < 0) {
				doubleHammerCount = 0;
			}
		}
	}

	public int getDoubleHammerCount() {
		synchronized (doubleHammerSyncObj) {
			return doubleHammerCount;
		}
	}

	public void refreshToolCount() {
		gameLayer.toolbar.updateToolCount();
	}

	/**
	 * 统计矮人的完结数量，适时结束游戏
	 */
	public synchronized void finishOneDwarf() {
		if (gameType == 1) {
			finishDwarfCount++;
			if (finishDwarfCount >= stageInfo.getDwarfCount() && !isFinished) {
				finishGame();
			}
		}
	}

	public synchronized void addKnockoutCount() {
		knockOutCount++;
	}

}
